import { Component } from 'react';
import { View } from '@tarojs/components'
import { countDownFormat } from '@/utils'
import './index.scss'

interface State{
    countDown: string
}
interface Props{
    time: number | string
    serverTime?: any
}

export default class Index extends Component<Props, any> {

    constructor (props) {
        super(props)
        this.state = {
            countDown: ''
        }
    }

    state:State

    UNSAFE_componentWillMount() { }
    componentDidMount() {
        this.countDownMd()
    }
    UNSAFE_componentWillReceiveProps(nextProps, nextContext) { }
    componentWillUnmount() {
        clearTimeout(this.clearCountDown)
    }
    componentDidShow() { }
    componentDidHide() { }
    componentDidCatchError() { }
    componentDidNotFound() { }
    dayTime: number = 86400000
    clearCountDown: any = null
    countDownMd () {
        let { time, serverTime } = this.props
        let countDown = ''
        if (this.clearCountDown) {
            clearTimeout(this.clearCountDown)
        }
        // 创建订单时间
        let createdAt = time * 1000
        // 待付款结束时间
        let timeEnd = createdAt + this.dayTime
        let newServerTime = serverTime || +new Date()
      //   let nowDate = serverTime * 1000
        let nowDate = newServerTime
        let liveTime = () => {
          if (nowDate < timeEnd) {
            // 当前时间小于结束时间，还在倒计时范围之内
            this.clearCountDown = setTimeout(liveTime, 1000)
            nowDate += 1000
          } else {
            clearTimeout(this.clearCountDown)
          }
          countDown = countDownFormat(+new Date(timeEnd - nowDate))
        //   console.log(timeEnd)
        //   console.log(countDown)
          this.setState({
            countDown
          })
        }
        liveTime()
    }
    render() {
        const { countDown } = this.state
        return (
            <View className='countdown'>
                <View className='time'>{countDown}</View>
            </View>
        )
    }
}
